<template>
  <div class="app-container" id='cardInfo'>
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
    	<!--<el-form-item label="代理商" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择" @change='getUser'>
				    <el-option
				      v-for="item in userOptions"
				      :key="item.userId"
				      :label="item.userName"
				      :value="item.userId">
				    </el-option>
				  </el-select>
      </el-form-item>-->
       <el-form-item label="代理商" prop='userName'>
           <el-select :value="queryParams.userName" placeholder='请选择代理商' :clearable='clearable' @clear="clearHandle" ref='chooseUserSearch'>
		        <el-option :value="queryParams.userName" label="" style='height:200px;overflow-y: scroll;width: 100%;background: white;'>
						  <el-tree  :data="userList" :props="props" :accordion="accordion"  @node-click="handleNodeClickSearch"></el-tree>
		       </el-option>
			</el-select>
        </el-form-item>
     <el-form-item label="ICCID" prop="iccid">
        <el-input
        	v-model = 'queryParams.iccid'
          placeholder="ICCID"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="MSISDN" prop="msisdn">
        <el-input
        	v-model = 'queryParams.msisdn'
          placeholder="MSISDN"
          clearable
          size="small"
        />
      </el-form-item>
       <el-form-item label="IMSI" prop="imsi">
        <el-input
        	v-model = 'queryParams.imsi'
          placeholder="IMSI"
          clearable
          size="small"
        />
      </el-form-item>
 			<el-form-item label="运营商" prop='ispType'>
         <el-select v-model="queryParams.ispType" placeholder="请选择">
				    <el-option key="1" label="中国移动" value="移动"></el-option>
				    <el-option key="2" label="中国联通" value="联通"></el-option>
				    <el-option key="3" label="中国电信" value="电信"></el-option>
				    </el-option>
				  </el-select>
      </el-form-item>
      <el-form-item label="卡状态" prop='status'>
        <el-select v-model="queryParams.status " placeholder="请选择">
				    <el-option key="0" label="其他" value="0"></el-option>
				    <el-option key="1" label="待激活" value="1"></el-option>
				    <el-option key="2" label="沉默期(库存)" value="2"></el-option>
				    <el-option key="3" label="测试期" value="3"></el-option>
				    <el-option key="4" label="正常" value="4"></el-option>
				    <el-option key="5" label="停机" value="5"></el-option>
				    <el-option key="6" label="已销号" value="6"></el-option>
				    </el-option>
				  </el-select>
      </el-form-item>
       <!--<el-form-item label="是否分配" prop='status'>
        <el-select v-model="queryParams.status " placeholder="请选择">
				    <el-option key="0" label="已分配" value="0"></el-option>
				    <el-option key="1" label="未分配" value="1"></el-option>
				    </el-option>
				  </el-select>
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          @click="daoru"
          v-hasPermi="['whty:card:dealCard']"
        >卡导入</el-button>

      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-s-check"
          size="mini"
   			  v-hasPermi="['whty:card:dealCard1']"
          @click="fenpei"
        >卡片分配</el-button>

      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-open"
          size="mini"
          @click="changeStatue"
          v-hasPermi="['whty:card:cardStatusUpdate']"
        >卡片状态变更</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-sort"
          size="mini"
          @click= 'updataStatue'
          v-hasPermi="['whty:info:cardInfoUpdate']"
          :disabled='isdisabledStatus'
        >数据更新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-s-order"
          size="mini"
          @click= 'rechargeCard'
          v-hasPermi="['whty:list:batchRechargeTest']"
        >批量充值</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click= 'deleteCard'
          v-hasPermi="['system:info:remove']"
        >批量删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" ref="postList" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ICCID" align="center">
      	<template slot-scope="scope">
      		 <el-link type="primary" class="buttonText" @click='cardDetiles(scope.row.iccid)'>{{scope.row.iccid}}</el-link>
      	</template>
      </el-table-column>
      <el-table-column label="MSISDN" align="center" prop="msisdn" />
      <el-table-column label="运营商" align="center" prop="ispType" />
      <el-table-column v-if='!isAent' label="代理商" align="center" prop="userName" />
      <el-table-column v-if='!isAent' label="卡来源" align="center" prop="upPlatform" />
      <el-table-column label="IMSI" align="center" prop="imsi" />
      <el-table-column label="主套餐" align="center" prop="pricingName" />
			<el-table-column label="计费结束日期" align="center" prop="createTime"  />
			<el-table-column label="导入时间" align="center" prop="importTime"  />
			<el-table-column label="当月流量" align="center" prop="flowTotal" :formatter="flowFormatAll"  />
			<el-table-column label="本月流量使用量" align="center" prop="monthFlowUsed" :formatter="flowFormatUsed"  />
			<el-table-column label="卡状态" align="center" prop="status" :formatter="stateFormat"  />
			<!--<el-table-column label="短信总量" align="center" prop="smsTotal"  />
			<el-table-column label="短信剩余量" align="center" prop="smsLeft"  />-->
			<el-table-column label="激活时间" align="center" prop="activateTime"  />
			<el-table-column label="过期时间" align="center" prop="lossTime"  />
			<el-table-column label="是否分配" align="center" prop="deptId" v-if='ismanager'>
			<template slot-scope="scope">
          <el-tag type="info" v-if="!scope.row.deptId">未分配</el-tag>
          <el-tag type="success" v-if="scope.row.deptId">已分配</el-tag>
        </template>
       </el-table-column>
			<el-table-column label="备注" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
         <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-pause"
            @click="stopCardBtn(scope.row)"
            v-hasPermi="['whty:card:cardHalt']"
          >停机</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="complexCardBtn(scope.row)"
            v-hasPermi="['whty:card:cardBegin']"
          >复机</el-button>
          <el-button
          	v-if='scope.row.status==1&&scope.row.upPlatform!="阿里"'
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="cardActiveCardBtn(scope.row)"
            v-hasPermi="['whty:card:cardActive']"
          >激活</el-button>
        </template>
      </el-table-column>
       <el-table-column label="卡信息" align="center" class-name="small-padding fixed-width">
       	 <template slot-scope="scope">
       	 	<!--<el-tooltip class="item" effect="dark" content="二维码" placement="left-start">
          <i class="el-icon-s-grid" @click='getCodeImage(scope.row)'></i>
          </el-tooltip>-->
          <el-tooltip class="item" effect="dark" content="综合信息" placement="top-start">
          <i style="color: blue;" v-hasPermi="['system:info:query']"   class="el-icon-s-fold" @click='getInfomation(scope.row.iccid)'></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 批量充值 -->
    <el-dialog title="批量充值" :visible.sync="openRecarge" width="800px" :close-on-click-modal='false'>
      <el-form ref="formRecharge" :model="rechargeForm" :rules="rules" label-width="80px"
    v-loading="loadingCz"
    element-loading-text="提交中"
    element-loading-background="rgba(255, 255, 255, 0.7)">
					 	<el-row>
					<el-col :span='9'>
						<el-form-item label="ICCID" prop="iccids">
         	  <el-input :autosize="{ minRows: 4, maxRows: 6}" v-model="rechargeForm.iccids" type="textarea"  placeholder="请输入内容, 多行请换行" @blur='changeIccids' />
        	  </el-form-item>
					</el-col>
					<el-col :span='10' :offset='2'>
						<el-upload
					  class="upload-demo"
					  action="/whty/list/importCardByRenew"
						:before-upload="beforeUpload"
					  :on-change="handleChangeRecarge"
					  :on-preview="handlePreviewRecarge"
					  :on-remove="handleRemoveRecarge"
					  :before-remove="beforeRemoveRecarge"
					  multiple
					  :limit="3"
					  :on-exceed="handleExceed"
					  :file-list="rechargeForm.fileList">
					  <el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
					<el-link type="primary" style='margin-top:20px;' @click='downLoadModelRecharge'>请下载模板文件</el-link>
					</el-col>
					</el-row>
					<el-form-item label="套餐类型" prop="chooseTc">
         	    <el-radio-group v-model="rechargeForm.chooseTc" @change='getTctype'>
						    <el-radio :label="0" value='0'>流量</el-radio>
						    <!--<el-radio :label="1" value='1'>语音</el-radio>
						    <el-radio :label="2" value='2'>短信</el-radio>
						    <el-radio :label="3" value='3'>混合</el-radio>-->
						  </el-radio-group>
        	</el-form-item>
        	<el-form-item label="套餐" prop="taoCan">
         	    <el-select v-model="rechargeForm.taoCan" @change='getTcListOne'>
						    <el-option v-for='item in taocanList' :label="item.pricingName" :value="item.pricingId"></el-option>
						  </el-select>
        	</el-form-item>
        	<el-form-item label="数量" prop="shuliang" >
        		<el-col :span='7'>
         	   <el-input type='text' v-model='rechargeForm.shuliang' @keyup.native="changeNum()" :disabled='upPlatformStr=="ali"'></el-input>
         	   </el-col>
        	</el-form-item>
        	<el-form-item label="总金额">
         	   <el-row style='color: red;'>￥{{rechargeForm.totalMoney}}</el-row>
        	</el-form-item>
        	<el-form-item label="生效方式" prop="shengxiao">
         	    <el-radio-group v-model="rechargeForm.shengxiao">
         	    	<el-radio v-for='item in effectTypeArrHtml' :label="item.value" value='item.value'>{{item.name}}</el-radio>
						    <!--<el-radio :label="1" value='1'>立即生效</el-radio>
						    <el-radio :label="2" value='2'>次月生效</el-radio>
						    <el-radio :label="3" value='3'>到期生效</el-radio>-->
						  </el-radio-group>
        	</el-form-item>
					</el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormImportRecharge">确 定</el-button>
        <el-button @click="cancelRecharge">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 卡片导入 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal='false'>
      <el-form ref="importForm" :model="importForm" :rules="rules" label-width="80px"
    v-loading="loadingdaoru"
    element-loading-text="文件上传中"
    element-loading-background="rgba(255, 255, 255, 0.7)" >
        <el-form-item label="代理商" prop='userName'>
           <el-select :value="importForm.userName" placeholder='请选择客户' :clearable='clearable' @clear="clearHandle" ref='chooseUserdaoru'>
		        <el-option :value="importForm.userName" label="" style='height:200px;overflow-y: scroll;width: 100%;background: white;'>
						  <el-tree  :data="userList" :props="props" :accordion="accordion"  @node-click="handleNodeClick"></el-tree>
		       </el-option>
					 </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="fileList">
        	<!--上传文件-->
          <el-col :span='8'>
          	<el-upload
					  class="upload-demo"
					  :before-upload="beforeUploadImport"
					  :on-change="handleChange"
					  :on-preview="handlePreview"
					  :on-remove="handleRemove"
					  :before-remove="beforeRemove"
					   action="/system/info/importData"
					   multiple
					  :limit="1"
					  :on-exceed="handleExceed"
					  :file-list="importForm.fileList">
					  <el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
          </el-col>
          <el-col :span='10' ><el-link type='primary' @click='downLoadModel'>点击下载模板文件</el-link></el-col>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="importForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormImport">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 卡片分配 -->
    <el-dialog :title="title" :visible.sync="openfenpei" width="500px" :close-on-click-modal='false'>
      <el-form ref="formfenpei" :model="fenpeiData" :rules="rules" label-width="80px">
        <el-form-item label="卡数量" prop="postName">
         <el-col :span='2' style='color:red;'>{{fenpeiData.totalNum}}</el-col>
        </el-form-item>
         <el-form-item label="代理商" prop="userName">
           <el-select :value="fenpeiData.userName" placeholder='请选择代理商' :clearable='clearable' @clear="clearHandle" ref='chooseUserfenpei'>
		        <el-option :value="fenpeiData.userName" label="" style='height:200px;overflow-y: scroll;width: 100%;background: white;'>
						  <el-tree  :data="userList" :props="props" :accordion="accordion"  @node-click="handleNodeClickfenpei"></el-tree>
		       </el-option>
					 </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="fenpeiData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormFenpei">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 卡状态跟新 -->
   <el-dialog :title="title" :visible.sync="openstatues" width="500px" :close-on-click-modal='false'>
      <el-form ref="formStatus" :model="cardStatus" :rules="rules" label-width="80px">
        <el-form-item label="卡数量" prop="totalNum">
         <el-col :span='2' style='color:red;'>{{cardStatus.totalNum}}</el-col>
        </el-form-item>
        <el-form-item label="状态" prop="cardStatu">
          <el-select v-model="cardStatus.cardStatu" placeholder="请选择">
						<el-option key="0" label="其他" value="0"></el-option>
				    <el-option key="1" label="待激活" value="1"></el-option>
				    <el-option key="2" label="沉默期(库存)" value="2"></el-option>
				    <el-option key="3" label="测试期" value="3"></el-option>
				    <el-option key="4" label="正常" value="4"></el-option>
				    <el-option key="5" label="停机" value="5"></el-option>
				    <el-option key="6" label="已销号" value="6"></el-option>
					</el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormStatus">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
     <!-- 显示二维码-->
    <el-dialog title="二维码" :visible.sync="openQcode" width="500px" :close-on-click-modal='false'>
    	<p style="text-align: center;"><img :src='imgbase64' /></p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeQcode">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {upload, listInfo,importTemplate,importData,userList,cardInfoUpdate,batchRechargeTest,importTemplate11,cardImport,getPriceList,importDataTest1,randomValue,importDataTestSubmit,cardHalt,cardBegin,cardActive,cardStatusUpdate,cardFenpeiSubmit,deleteCard,getCodeImage,cardImportUpdate,normalRole,webstock } from "@/api/system/info";
//import { getUserList1 } from "@/api/order/list";

import { Loading } from 'element-ui';
import { treeselect } from "@/api/system/dept";
export default {
  name: "Post",
  props:{
	   	 props: {
	      children: 'children',
	      label: 'label',
	    },
       	 /* 自动收起 */
	    accordion:{
	      type:Boolean,
	      default:()=>{ return false }
			},
			 /* 可清空选项 */
	    clearable:{
	      type:Boolean,
	      default:()=>{ return true }
			},
     },
  data() {
    return {
    	//上传文件list
//  	fileList: [],
			isAent:true,
			ismanager:false,  //是否admin
      // 遮罩层
      loading: true,
      loadingdaoru:false,  //导入遮罩
      loadingdaorublack:false,  //导入遮罩
      loadingCz:false,   //充值遮罩
      isdisabledStatus:false,
      // 选中数组
      ids: [],
      iccids:[],
      ispTypes:[],  //运营商数组
      choosedCardStatus:[],  //选中的卡状态
      ispType:'',  //选中卡的运营商类型
      upPlatform:'',  //选中的卡来源
      upPlatformStr:'',  //选中的卡来源
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      cardList: [],
      // 卡片分配弹出层
      openfenpei:false,
      // 卡片状态弹出层
      openstatues:false,
      openRecarge:false,
      //二维码弹出层
      openQcode:false,
      imgbase64:'',
      taocan:undefined,
      taocanType:undefined,
      num:'',  //随机数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ispType:'',  //运营商
        iccid: undefined,
        msisdn: undefined,
        imsi:undefined,
        status: undefined,
        userName:'',
        deptId:''
//      agentId:'',
//      enterpriseId:''
      },

      rechargeForm:{  ///批量充值
      	iccids:'',
      	chooseTc:0,   //套餐类型
      	taoCan:'',
      	shuliang:'',
      	shengxiao:'',
      	fileList:[],    //批量充值 上传文件的列表
      	fileInfo:{},//批量充值 上传文件的信息
      	pricingName:'',
      	pricingId:'',
      	singlePrice:'',  //单价
      	monthCost:'',
      	count:'',  //数量
      	totalMoney:0,  //总价
      	upPlatformStr:'',  //卡来源
      },
      effectTypeArrHtml:'',   //生效类型
      taocanList:[],  //套餐列表
      userOptions:[],
      // 表单参数
      form: {},
       //卡导入运营商下拉参数
      importForm:{
      	fileList:[],
      	remark:'',
//	  		agentId:undefined,
//	  		enterpriseId:undefined,
	  		userName:undefined,
			  deptId:undefined,
	  		key:undefined
      },
      daoruFd:{},   //卡导入的列表FD
      //卡分配数据
	  	fenpeiData:{
	  		totalNum:0,
	  		userfenpei:undefined,
//	  		agentId:undefined,
//	  		enterpriseId:undefined,
				deptId:undefined,
	  		userName:undefined,
	  		remark:undefined
	  	},
	  	//卡状态变更：
	  	cardStatus:{
	  		totalNum:0,
	  		cardStatu:undefined,
	  		iccids:''
	  	},
      userList:[],  //用户列表
      // 表单校验
      rules: {
      	chooseTc:[{ required: true}],
				iccids:[{ required: true, message: "ICCID不能为空", trigger: "blur" }],
				shuliang:[{ required: true, message: "数量不能为空", trigger: "blur" }],
				taoCan:[{ required: true, message: "套餐不能为空", trigger: "change" }],
				cardStatu:[{ required: true, message: "卡状态不能为空", trigger: "change" }],
				fileList:[{ required: true, message: "请选择上传文件", trigger: "change" }],
      }
    };
  },
  created() {
  	normalRole().then((res)=>{
  		if(res.data){  //true是管理员
  			this.ismanager = true;
  			this.isAent = false;
  		}
  	})
    this.getList();
     treeselect().then((res)=>{  //用户列表接口
	    this.userList = res.data;
	 })
  },
  methods: {
  	handleNodeClickSearch(a,e){
			let subList=a.children;
			if (typeof(subList) != "undefined" && typeof(subList.length) != "undefined" && subList.length > 0) {
			    return;
			}
	  	this.queryParams.deptId = a.id;
  		this.queryParams.userName = a.label;
  		this.$refs.chooseUserSearch.blur();
  	},
  	handleNodeClick(a,e){  //点击选着客户  卡导入弹框
			let subList=a.children;
			if (typeof(subList) != "undefined" && typeof(subList.length) != "undefined" && subList.length > 0) {
			    return;
			}
	  	this.importForm.deptId = a.id;
  		this.importForm.userName = a.label;
  		this.$refs.chooseUserdaoru.blur();
  	},
  	handleNodeClickfenpei(a,e){  //卡分配  客户
			let subList=a.children;
			if (typeof(subList) != "undefined" && typeof(subList.length) != "undefined" && subList.length > 0) {
			    return;
			}
	  	this.fenpeiData.deptId = a.id;
	  	this.fenpeiData.userName = a.label;
  		this.$refs.chooseUserfenpei.blur();
  	},
  	clearHandle(){  //清楚选项  卡导入弹框
  		this.importForm.userName = '';
  		this.importForm.deptId = undefined;
  		this.fenpeiData.userName = '';
  		this.fenpeiData.deptId = undefined;
  		this.queryParams.userName = '';
  		this.queryParams.deptId = undefined;
  	},
  	downLoadModelRecharge(){  //下载充值模板
  		importTemplate11().then(response => {
        this.download(response.msg);
      });
  	},
  	beforeUpload(file){  //上传充值卡号文件
  		 var  fileJson = {};
  		 var fd = new FormData();
       fd.append('file',file);//传文件
       fd.append('name',file.name);//传文件
       fileJson.name = file.name;
       this.loadingCz = true;
       console.log(this.fileList);
       cardImport(fd).then(res=>{
			 if(res.code=='200'){
			 	this.rechargeForm.iccids+=res.msg;
			 	this.loadingCz = false;
			 	this.rechargeForm.fileList.push(fileJson);
			 	console.log(res);
    		}
			 }).catch((res)=>{
			 	  this.$message.error('上传失败');
			 })
  	},
    submitFormImportRecharge(){  //提交充值按钮
    	this.$refs["formRecharge"].validate(valid => {
			        if (valid) {
			        	var totalPrice = 0;
			        	var chargeData = {};
			        	chargeData.pricingName = this.rechargeForm.pricingName;  //套餐名称
			        	chargeData.pricingId = this.rechargeForm.pricingId;  //套餐ID
			        	chargeData.count = this.rechargeForm.shuliang;  //套餐数量
			        	chargeData.pricingType = this.rechargeForm.chooseTc;  //套餐类型
			        	chargeData.singlePrice = this.rechargeForm.singlePrice;
			        	chargeData.totalMoney = this.rechargeForm.totalMoney;
			        	chargeData.iccids = this.rechargeForm.iccids;  //卡号列表
			        	chargeData.effectiveType = this.rechargeForm.shengxiao;  //生效方式
			        	chargeData.upPlatform = this.upPlatformStr;//卡来源
							batchRechargeTest(chargeData).then(response => {
							if(response.code==200){
							  this.$message({
					          message: '充值成功！',
					          type: 'success'
					        });
					        setTimeout(()=>{
					        	this.getList();
					        },3000)
					        this.openRecarge = false;
							}else{
									this.$message.error('充值失败');
								}
				        console.log(response);
				      });
			        }
			})
    },
    uniq(array){  //去重
    var temp = []; //一个新的临时数组
    for(var i = 0; i < array.length; i++){
        if(temp.indexOf(array[i]) == -1){
            temp.push(array[i]);
        }
    }
    return temp;
	},
    rechargeCard(val){   //点击批量充值
    //	this.openRecarge = true;
    	this.rechargeForm.iccids = undefined;
    	var isChooseFlag = false;
    	var yunyingFlag = false;
    	var upPlatformFlag = false;
    	var statusFlag = true;
    	if(this.cardList.length>0){
    		isChooseFlag = true;
    	}else{
    		 this.$message({
          message: '请选择需要充值的卡',
          type: 'warning'
       	 });
       	 return;
    	}
    	if(this.uniq(this.ispTypes).length==1){
    		this.ispType = this.uniq(this.ispTypes)[0];
    		yunyingFlag = true;
    	}else{
    			this.$message({
          message: '选中的卡所属运营商不一致！',
          type: 'warning'
        });
        return;
    	}
    	if(this.uniq(this.upPlatform).length==1){
    		this.upPlatformStr = this.uniq(this.upPlatform)[0];
    		if(this.upPlatformStr=='ali'){
    			this.rechargeForm.shuliang = '1'
    		}
    		upPlatformFlag = true;
    	}else{
    			this.$message({
          message: '选中的卡来源不一致！',
          type: 'warning'
        });
        return;
    	}
    		for(var i=0;i<this.choosedCardStatus.length;i++){
      		if(this.choosedCardStatus[i]!=4){
	      			this.$message({
		          message: '所选卡中有非可充值的卡状态，请重新选择',
		          type: 'warning'
		        });
		       statusFlag = false;
      		}
      	}
    		if(isChooseFlag&&yunyingFlag&&statusFlag&&upPlatformFlag){
    			this.openRecarge = true;
    		}	
      	var firstispTypes = this.ispTypes[0];
        for(var i=0;i<this.cardList.length;i++){
          if(this.rechargeForm.iccids!=undefined){
            this.rechargeForm.iccids = this.rechargeForm.iccids + this.cardList[i].iccid + ",";
          }else{
            this.rechargeForm.iccids = this.cardList[i].iccid + ",";
          }
        }
        this.getTctype(0);
      
    },
    getTctype(type){  //切换套餐类型
      			var taocanData = {'pricingType':type,'ispType':this.ispType,'upPlatform':this.upPlatformStr}
      			getPriceList(taocanData).then((res)=>{
      				this.taocanList = res.data;
      			})
    },
    changeNum(){//修改数量
    	var iccidsLength = this.rechargeForm.iccids.split(',').length-1;
    	this.rechargeForm.totalMoney = iccidsLength*this.rechargeForm.singlePrice*this.rechargeForm.shuliang;
    },
    changeIccids(){  //修改卡号
    	var iccidsLength = this.rechargeForm.iccids.split(',').length-1;
    	console.log(iccidsLength);
    	this.rechargeForm.totalMoney = iccidsLength*this.rechargeForm.singlePrice*this.rechargeForm.shuliang;
    },
    getTcListOne(a){  //点击选中某个套餐
    	console.log(a);
    	var effectTypeArr = [];
    	var effectTypeArrHtml = [];
    	for(var i=0;i<this.taocanList.length;i++){
    		if(a==this.taocanList[i].pricingId){  //套餐ID相等
    			this.rechargeForm.singlePrice = this.taocanList[i].monthCost;
    			this.rechargeForm.pricingName = this.taocanList[i].pricingName;
    			this.rechargeForm.pricingId = this.taocanList[i].pricingId;
    			effectTypeArr = (this.taocanList[i].effectType).split(',');   //生效类型
    		}
    	}
    	console.log(effectTypeArr);
    	for(var i=0;i<effectTypeArr.length;i++){
    		if(effectTypeArr[i]=='0'){
    			effectTypeArrHtml.push({value:0,name:'立即生效'})
    		}else if(effectTypeArr[i]=='1'){
    			effectTypeArrHtml.push({value:1,name:'次月生效'})
    		}else if(effectTypeArr[i]=='2'){
    			effectTypeArrHtml.push({value:2,name:'到期生效'})
    		}
    	}
    	console.log(effectTypeArrHtml);
    	this.effectTypeArrHtml = effectTypeArrHtml;
    	var iccidsLength = this.rechargeForm.iccids.split(',').length-1;
    	this.rechargeForm.totalMoney = iccidsLength*this.rechargeForm.singlePrice*this.rechargeForm.shuliang;
    },
    cancelRecharge(){
      this.openRecarge = false;
    },
     /** 查询卡信息列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams);
      listInfo(this.queryParams).then(response => {
      	console.log(response);
        this.postList = response.rows;
        this.iccids =  response.rows.map(item=>item.iccid);
        this.total = response.total;
        this.fenpeiData.totalNum = response.total;
        this.cardStatus.totalNum = response.total;
        this.loading = false;
        this.userListFn();
      });
    },
    userListFn(){
    	var userArr = [];
//  	userList().then((res)=>{
//  		this.userOptions = res.rows;
//  		console.log(res);
//  	})
    },
    getUser(a){  //搜索  获取用户id
    	console.log(a);
    	this.queryParams.userId = a;
    },
    updataStatue(){  //状态跟新
    	var iccids = this.iccids;
    	var newIdsStr = '';
    	for(var i=0;i<iccids.length;i++){
    		newIdsStr+=iccids[i]+','
    	}
    	this.isdisabledStatus = true;
    	cardInfoUpdate(newIdsStr).then((res)=>{
    		if(res.code=='200'){
    			this.$message({
          message: '一共'+res.data.cardNumber+'张卡  更新完成需要'+res.data.time+'s',
          type: 'success'
        });
        this.getList();
        this.isdisabledStatus = false;
    		}else{
    			 this.$message.error('状态更新失败');
    		}
    	}).catch((res)=>{
    		 this.$message.error('状态更新失败');
    		  this.isdisabledStatus = false;
    	})
    },
    stateFormat(row){
			if(row.status==0){
				return '其他'
			}else if(row.status==1){
				return '待激活'
			}else if(row.status==2){
				return '沉默期（库存）'
			}else if(row.status==3){
				return '测试期'
			}else if(row.status==4){
				return '正常'
			}else if(row.status==5){
				return '停机'
			}else if(row.status==6){
				return '已销号'
			}
    },
    flowFormatAll(row){
    	if(row.status==1){
    		return '0.00MB'
    	}else{
    		return (row.flowTotal/1024).toFixed(2)+'MB';
    	}
    },
    flowFormatUsed(row){
    	return (row.monthFlowUsed/1024).toFixed(2)+'MB';
    },
    /** 下载模板 */
   downLoadModel(){
   	importTemplate().then(response => {
   				console.log(response);
        this.downloadCardList(response.msg);
    });
   },
    /** 导入 */
    daoru() {
      this.open = true;
       treeselect().then((res)=>{  //用户列表接口
	    	this.userList = res.data;
	    })
    },
    //卡片导入下载模板
    beforeUploadImport(file){
    	var fileJson = {};
    	var fd = new FormData();
       fd.append('file',file);//传文件
       fd.append('name',file.name);//传文件
       this.daoruFd = fd;
       fileJson.name = file.name;
       this.importForm.fileList.push(fileJson);
       upload( this.daoruFd).then((res)=>{
       		console.log(res)
       })
    },
    fenpei(){
    	this.reset();
    	if(this.ids.length==0){
    		this.$message.error('请选择待分配卡片');
    	}else{
    		this.openfenpei = true;
    	}
    	 treeselect().then((res)=>{  //用户列表接口
	  	 	console.log(res);
	    	this.userList = res.data;
	    })
    },
    /** 更新状态 */
    changeStatue(){
    	this.reset();
    	if(this.ids.length==0){
    		this.$message.error('请选择待变更卡片');
    	}else{
    		this.openstatues = true;
    	}
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openfenpei = false;
      this.openstatues = false;
      this.loadingdaoru = false; //卡导入遮罩
      this.loadingCz = false;  //充值遮罩
      this.importForm.fileList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
    	console.log(this.queryParams);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.userName='';
      this.queryParams.agentId='';
      this.queryParams.enterpriseId='';
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.ispTypes = selection.map(item => item.ispType);
      this.upPlatform = selection.map(item => item.upPlatform);
      this.iccids = selection.map(item => item.iccid);
      this.choosedCardStatus = selection.map(item => item.status);
      this.single = selection.length!=1
      this.multiple = !selection.length
      this.cardList = selection;
      this.fenpeiData.totalNum = selection.length;
      this.cardStatus.totalNum = selection.length;

    },
    TaocanSelectionChange(selection){
      console.log(selection);
    },
     /** 卡分配提交按钮 */
    submitFormFenpei: function() {
      this.$refs["formfenpei"].validate(valid => {
        if (valid) {
        	var iccidsStr = '';
        	for(var i=0;i<this.iccids.length;i++){
        		iccidsStr+=this.iccids[i]+','
        	}
        	 var fenpeiData = {};
        	 fenpeiData.iccids =iccidsStr;
//	     		 fenpeiData.agentId = this.fenpeiData.agentId;
//	     		 fenpeiData.enterpriseId = this.fenpeiData.enterpriseId;
						fenpeiData.deptId = this.fenpeiData.deptId;
	     		 console.log(fenpeiData);
					cardFenpeiSubmit(fenpeiData).then((res)=>{
						console.log(res);
						if(res.code==200){
					  this.$message({
			          message: '分配成功',
			          type: 'success'
			        });
			        this.getList();
						}
						   this.openfenpei = false;
					}).catch(()=>{
						this.getList();
					})
        }
      });

    },
     /** 卡状态跟新提交按钮 */
    submitFormStatus: function() {
      this.$refs["formStatus"].validate(valid => {
        if (valid) {
        	var cardStatus = {};
        	var iccidsStr = '';
        	for(var i=0;i<this.iccids.length;i++){
        		iccidsStr+=this.iccids[i]+','
        	}
        	cardStatus.iccids = iccidsStr;
        	cardStatus.totalNum = this.cardStatus.totalNum;
        	cardStatus.status = this.cardStatus.cardStatu;
					cardStatusUpdate(cardStatus).then((res)=>{
						if(res.code==200){
							 this.$message({
			          message: '修改成功',
			          type: 'success'
			        });
			        this.getList();
						}
						this.openstatues = false;
					})
        }
      });
    },
    submitFormImport:function(){  //卡导入提交按钮
    	this.$refs["importForm"].validate(valid => {
        if (valid) {
 					var newImportForm = {};
        	newImportForm.remark = this.importForm.remark;
        	newImportForm.deptId = this.importForm.deptId;
        	newImportForm.userName = this.importForm.userName;
        	this.num = Math.random().toFixed(4);
        	this.daoruFd.append('remark',this.importForm.remark);
        	this.daoruFd.append('deptId',this.importForm.deptId);
        	this.daoruFd.append('userName',this.importForm.userName);
        	this.daoruFd.append('randomColumn',this.num);
        	this.loadingdaoru = true;
//      	setTimeout(()=>{
//      		randomValue(random).then((res)=>{
//      		if(res.code=='200'){
//      				this.loadingdaoru = false;
//							 	this.getList();
//							 	this.$store.dispatch("publicCardInfo/updataAllCardInfo");
//							 	this.open=false;
//			      		this.importForm.fileList = [];
//			      		this.$message({
//				          message: '上传成功，后台处理更新中，请稍后',
//				          type: 'success'
//				        });
//      		}
//      	}).catch((res)=>{
//      		this.getList();
//				 		this.loadingdaoru = false;
//      	})
//      	},2000)
        	this.initWebSocket();
	        importDataTest1(this.daoruFd).then(res=>{
	       	console.log(res);
				 if(res.code=='200'){
//				 	var key = res.msg.split('=')[1];
//				 	this.importForm.key = key;
//				 	newImportForm.key = this.importForm.key;
	      
										
	    		}
//				 console.log(newImportForm);
//				 importDataTestSubmit(newImportForm).then((res)=>{
//      			console.log(res);
//      			if(res.code==200){
//      				this.loadingdaoru = false;
//      				 this.open=false;
//      				 this.importForm.fileList = [];
//				         this.getList();
//				         this.$store.dispatch("publicCardInfo/updataAllCardInfo");
//      			}
//      			if(res.code==200){
//						cardImportUpdate(key).then((res)=>{   //卡导入状态更新
//						if(res.code=='200'){
//			    			this.loadingdaoru = false;
//				        this.importForm.fileList = [];
//				        this.getList();
//				        this.$store.dispatch("publicCardInfo/updataAllCardInfo");
//	        			}
//	        			 this.open=false;
//	        			 this.$message({
//				          message: '提交成功  更新完成花费'+res.data.time+'s',
//				          type: 'success'
//						})
//				    	}).catch((res)=>{
//				    		 this.loadingdaoru = false;
//				    		 this.$message.error('卡导入更新失败');
//				    	})
//					 }
//      		}).catch((res)=>{
//      			this.getList();
//      			this.loadingdaoru = false;
//      		})
				 }).catch((res)=>{
				 	this.getList();
				 	this.loadingdaoru = false;
				 })
        }
        
      });
    },
    stopCardBtn(row){  //停机操作
    	console.log(row);
    	if(row.status!='4'){  //不是正常的状态
    		this.$message({
	          message: '此卡状态不能进行停机操作',
	          type: 'warning'
	        });
	        return;
    	}
    	var cardHaltData = {
    		iccid:row.iccid,
    	}
    	console.log(cardHaltData);
    	cardHalt(cardHaltData).then((res)=>{
    		console.log(res);
    		if(res.data){
    			  this.$message({
	          message: '停机成功',
	          type: 'success'
	        });
	          this.getList();
    		}else{
    			this.$message.error('停机失败');
    		}
    	})
    },
    complexCardBtn(row){  //复机操作
    	if(row.status!='5'){  //不是停机状态
    		this.$message({
	          message: '此卡状态不能进行复机操作',
	          type: 'warning'
	        });
	        return;
    	}
    	var cardBeginData = {
	    		iccid:row.iccid,
	    	}
    	cardBegin(cardBeginData).then((res)=>{
    		console.log(res);
	    		if(res.data){
    			  this.$message({
	          message: '复机成功',
	          type: 'success'
	        });
	          this.getList();
    		}else{
    			this.$message.error('复机失败');
    		}
    	})
    },
    cardActiveCardBtn(row){  //激活操作
    	var cardActiveData = {
	    		iccid:row.iccid,
	    	}
    	cardActive(cardActiveData).then((res)=>{
    		console.log(res);
	    		if(res.code=='200'){
    		 this.$message({
	          message: '激活成功',
	          type: 'success'
	        });
	          this.getList();
    		}else{
    			this.$message.error('激活失败');
    		}
    	})
    },
    deleteCard(){  //删除卡信息列表
    	 this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var idsStr = '';
		    	for(var i=0;i<this.ids.length;i++){
		    		idsStr+=this.ids[i]+','
		    	}
		    	deleteCard(idsStr).then((res)=>{
		    		console.log(res);
		    		if(res.code==200){
		    			  this.$message({
			          message: '删除成功',
			          type: 'success'
			        });
			         this.queryParams.pageNum = 1;
     					 this.getList();
     					 this.$store.dispatch("publicCardInfo/updataAllCardInfo");
		    		}
		    	})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });	
    },
    getCodeImage(data){  //查看二维码
    	getCodeImage(data.iccid).then((res)=>{
    		console.log(res);
    		this.imgbase64 = 'data:image/jpeg;base64,'+res.msg;
    		this.openQcode = true;
    	}).catch((res)=>{
    		console.log(res);
    	})
    },
    getInfomation(id){  //点击跳转综合信息
    	this.$router.push({path:`/communicationInfo/cardList/cardInformation/${id}`})
    },
    closeQcode(){
    	this.openQcode = false;
    },
//  获取文件
    handleChange(file,fileList){
    	console.log(file);
    },
     handleRemove(file, fileList) {
     	  this.importForm.fileList = [];
        console.log(file, fileList);
      },
      handlePreview(file) {
//      console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`每次只能传一个文件,如需替换文件,请先删除`);
      },
      beforeRemove(file, fileList) {

        return this.$confirm(`确定移除 ${ file.name }？`);
      },

      //  获取文件  批量充值
    handleChangeRecarge(file,fileList){
    	console.log(file);

    },
     handleRemoveRecarge(file, fileList) {
     	 	this.rechargeForm.fileList = [];
        console.log(file, fileList);
      },
      handlePreviewRecarge(file) {
        console.log(file);
      },
      handleExceedRecarge(files, fileList) {
        this.$message.warning(`每次只能传一个文件,如需替换文件,请先删除`); 
      },
      beforeRemoveRecarge(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      cardDetiles(id){//点击显示详情
      	this.rechargeForm.fileList = [];
      	this.$router.push({path:`/communicationQcode/cardList/cardDetiles/${id}`});
      },
      	initWebSocket: function () {                
			// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https  
				
				this.websock = new WebSocket('http://10.8.4.160:8080/prod-api/websocket/'+this.num);                
				this.websock.onopen = this.websocketonopen;                
				this.websock.onerror = this.websocketonerror;                
				this.websock.onmessage = this.websocketonmessage;                
				this.websock.onclose = this.websocketclose;              
			},              
			websocketonopen: function () {  
	    		this.loadingdaorublack = Loading.service({
          lock: true,
          text: '导入中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        	fullscreen:false
        });
				console.log("WebSocket连接成功"); 
				 	this.open=false;
				
//				webstock(this.num).then((res)=>{   
//				if(res.code=='200'){
//	        this.loadingdaorublack.close();
//	        this.loadingdaoru = false;
//				 	this.getList();
//				 	this.$store.dispatch("publicCardInfo/updataAllCardInfo");
//				 	this.open=false;
//    		this.importForm.fileList = [];
//    		this.$message({
//	          message: '导入成功',
//	          type: 'success'
//	        });
//				}
//			})
			},              
			websocketonerror: function (e) {                
				console.log("WebSocket连接发生错误");              
			},              
			websocketonmessage: function (e) {                
				console.log(e.data);     
				  this.loadingdaorublack.close();
	        this.loadingdaoru = false;
				 	this.getList();
				 	this.$store.dispatch("publicCardInfo/updataAllCardInfo");
				
      		this.importForm.fileList = [];
      		this.$message({
	          message: '导入成功',
	          type: 'success'
	        });// console.log(e);
	        this.websocketclose();   
			},              
			websocketclose: function (e) {                
				console.log("connection closed (" + e.code + ")");              
			},              
			getWebsocket:function(){                
			
		 }  
  }

};
</script>
